package cn.com.headfree.mouldshow.service.impl;

import cn.com.headfree.callback.call.FileServerCall;
import cn.com.headfree.entity.IscUser;
import cn.com.headfree.mouldshow.dao.IscUserDao;
import cn.com.headfree.mouldshow.dao.UserDataInfoDao;
import cn.com.headfree.mouldshow.service.IscUserService;
import cn.com.headfree.mouldshow.service.ProveFileExportService;
import cn.com.headfree.mouldshow.service.UserDataInfoService;
import cn.com.headfree.util.ZipGenerateUtils;
import cn.com.headfree.vo.BusinessIdsVo;
import cn.com.headfree.vo.file.DealFileVo;
import com.gta.edu.sdk.util.StringUtil;
import feign.Response;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

/**
 * 佐证材料导出
 */
@Service("proveFileExportService")
@Transactional
public class ProveFileExportServiceImpl implements ProveFileExportService {

	private static final Logger log = LogManager.getLogger(ProveFileExportServiceImpl.class);

	// 临时下载路径
	@Value("${file_temp_path}")
	private String file_temp_path;

	@Autowired
	private FileServerCall fileServerCall;

	@Autowired
	private UserDataInfoService userDataInfoService;

	@Autowired
	private UserDataInfoDao userDataInfoDao;

	@Override
	public void downloadFiles(String erpNo,String sysCode, String businessNode, HttpServletRequest request,
							  HttpServletResponse response) {
		InputStream inputStream = null;
		try {
			String fileId = null;
			String fileName = null;
			String dirName = null;
			List<BusinessIdsVo> list= userDataInfoService.getBusinessIdByErpNo(erpNo);
			for (BusinessIdsVo bvo : list) {
				String businessId=bvo.getBusinessId();
				if(!StringUtil.isNullOrEmpty(businessId)) {
					List<DealFileVo> lists = userDataInfoDao.getFilesByBusinessId(businessId,businessNode);
					for(DealFileVo f:lists) {
						File file = new File(file_temp_path);
						if (!file.exists()) {
							file.mkdirs();
						}
						fileId = f.getFileId();
						fileName = f.getFileName();
						dirName = bvo.getTypeName();
						// 下载文件
						if (fileId != null) {
							try {
								Response resp = fileServerCall.downloadFile(fileId);
								// 判断是否下载成功
								if (resp.status() == 200) {
									Response.Body body = resp.body();
									inputStream = body.asInputStream();
									downloadSingleFile(inputStream, fileName, dirName);
								}
							} catch (Exception e) {
								log.error("下载文件失败！", e);
							}
						}
					}
				}

			}
			File f = new File(file_temp_path);
			File files[] = f.listFiles();
			ZipGenerateUtils.createZip(request, response, file_temp_path, "附件.rar");
			ZipGenerateUtils.ZipFiles(request, response, files, "附件.rar");
			deleteDirectory(file_temp_path);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private String downloadSingleFile(InputStream inputStream, String fileName, String dirName) {
		FileOutputStream fileOut = null;
		BufferedInputStream bis = new BufferedInputStream(inputStream);
		// 判断文件的保存路径后面是否以/结尾
		if (!file_temp_path.endsWith("/")) {
			file_temp_path += "/";
		}
		if (!dirName.endsWith("/")) {
			dirName += "/";
		}
		File f = new File(file_temp_path + dirName);
		if (!f.exists()) {
			f.mkdirs();
		}
		// 写入到文件（注意文件保存路径的后面一定要加上文件的名称）
		try {
			fileOut = new FileOutputStream(file_temp_path + dirName + fileName);
			BufferedOutputStream bos = new BufferedOutputStream(fileOut);
			byte[] buf = new byte[4096];
			int length = bis.read(buf);
			// 保存文件
			while (length != -1) {
				bos.write(buf, 0, length);
				length = bis.read(buf);
			}
			bos.close();
			bis.close();
			return null;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 删除目录（文件夹）以及目录下的文件
	 *
	 * @param sPath 被删除目录的文件路径
	 * @return 目录删除成功返回true，否则返回false
	 */
	public boolean deleteDirectory(String sPath) {
		// 如果sPath不以文件分隔符结尾，自动添加文件分隔符
		if (!sPath.endsWith(File.separator)) {
			sPath = sPath + File.separator;
		}
		File dirFile = new File(sPath);
		// 如果dir对应的文件不存在，或者不是一个目录，则退出
		if (!dirFile.exists() || !dirFile.isDirectory()) {
			return false;
		}
		boolean flag = true;
		// 删除文件夹下的所有文件(包括子目录)
		File[] files = dirFile.listFiles();
		for (int i = 0; i < files.length; i++) {
			// 删除子文件
			if (files[i].isFile()) {
				flag = deleteFile(files[i].getAbsolutePath());
				if (!flag)
					break;
			} // 删除子目录
			else {
				flag = deleteDirectory(files[i].getAbsolutePath());
				if (!flag)
					break;
			}
		}
		if (!flag)
			return false;
		// 删除当前目录
		if (dirFile.delete()) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 删除单个文件
	 *
	 * @param sPath 被删除文件的文件名
	 * @return 单个文件删除成功返回true，否则返回false
	 */
	public boolean deleteFile(String sPath) {
		boolean flag = false;
		File file = new File(sPath);
		// 路径为文件且不为空则进行删除
		if (file.isFile() && file.exists()) {
			file.delete();
			flag = true;
		}
		return flag;
	}
}
